package cn.edu.zjicm.wordsnet_d.download;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.XmlResourceParser;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.ShowListenApp;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.datapersistent.FileManager;
import cn.edu.zjicm.wordsnet_d.handler.LoadWindowHandler;
import cn.edu.zjicm.wordsnet_d.net.Client;
import cn.edu.zjicm.wordsnet_d.synchronize.UserInterface;
import cn.edu.zjicm.wordsnet_d.util.DateTimeUtils;

public class UpdateManager {

	private Context mContext;
	public static int curVersionCode = 0;
	public static String curVersionName = null;

	int newVersionCode;
	static String apkFileName = null;
	String newVersionName = "";
	String newVersionDescription = "";

	private View mMask;

	// 网络的判断
	private JudgeNetwork jNetwork;
	private boolean changeRemind = false;

	// 进度条
	private TextView updateHideButton;
	private TextView confirmButton;
	private TextView cancleButton;

	private TextView updateProgressText;
	private ProgressBar updateProgressBar;

	private PopupWindow mUpdateWindow;
	private PopupWindow mUpdateAskWindow;

	// 通知UI刷新的handler和msg常量
	private static final int MSG_VERSION_CODE = 1;
	private static final int DOWNLOADING = 2;
	private static final int BAD_NETWORK = 4;
	public static boolean showWindowFlag = true;

	private boolean autoCheckUpdateFlag = false;
	Handler loadWindowHandler;

	public UpdateManager(Context context, int curVersionCode) {
		this.mContext = context;
		loadWindowHandler = new LoadWindowHandler(mContext);
	}

	public UpdateManager(Context context, int curVersionCode, boolean autoCheckUpdateFlag) {
		this(context, curVersionCode);
		this.autoCheckUpdateFlag = autoCheckUpdateFlag;
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (!((Activity) mContext).isFinishing()) {
				switch (msg.what) {
				case MSG_VERSION_CODE:
					newVersionCode = (Integer) msg.obj;
					if (newVersionCode > curVersionCode) {
						mHandler.post(showUpdate);
					} else {
						if (!autoCheckUpdateFlag)
							Toast.makeText(mContext, "已经更新到最新版本", Toast.LENGTH_SHORT).show();
					}
					if (autoCheckUpdateFlag)
						AppPreference.setAutoCheckUpdateDate(mContext, DateTimeUtils.getDate());
					break;
				case DOWNLOADING:
					Toast.makeText(mContext, "新版本正在下载...", Toast.LENGTH_SHORT).show();
					break;
				case BAD_NETWORK:
					if (!autoCheckUpdateFlag)
						Toast.makeText(mContext, UserInterface.MSG_BAD_NETWORK_STRING, Toast.LENGTH_LONG).show();
					break;
				default:
					break;
				}
			}
		};
	};

	public static void getCurVersion(Context mContext) {
		try {
			PackageInfo packageInfo = mContext.getPackageManager().getPackageInfo("cn.edu.zjicm.wordsnet_d", 0);
			curVersionCode = packageInfo.versionCode;
			curVersionName = packageInfo.versionName;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 如果已下载知米听力，启动知米听力；否则进入知米听力的介绍页面，可下载知米听力
	public static void downloadOrStartZhimiListenApp(Context mContext) {
		if (UpdateManager.isZhimiListenInstalled(mContext))
			UpdateManager.startZhimiListen(mContext);
		else
			ShowListenApp.startActivity(mContext);
	}

	// 判断知米听力是否安装
	public static boolean isZhimiListenInstalled(Context mContext) {
		PackageInfo packageInfo = null;
		try {
			packageInfo = mContext.getPackageManager().getPackageInfo("cn.edu.zjicm.listen", PackageManager.GET_ACTIVITIES);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			packageInfo = null;
		}
		// if(packageInfo == null)
		// Log.e("知米听力", "未安装");
		// else
		// Log.e("知米听力", "已安装");
		return packageInfo != null;
	}

	// 启动知米听力
	public static void startZhimiListen(Context mContext) {
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		ComponentName cn = new ComponentName("cn.edu.zjicm.listen", "cn.edu.zjicm.listen.activity.WelcomeActivity");
		intent.setComponent(cn);
		mContext.startActivity(intent);
	}

	// 软件自动更新，三天执行一次
	public static boolean autoCheckUpdate(Context mContext) {
		int theDayBeforeYestorday = DateTimeUtils.getTheDayBeforeYestorday();
		int lastAutoCheckUpdateDate = AppPreference.getAutoCheckUpdateDate(mContext);
		boolean result = false;
		if (lastAutoCheckUpdateDate == -1 || lastAutoCheckUpdateDate < theDayBeforeYestorday) {
			UpdateManager.getCurVersion(mContext);
			new UpdateManager(mContext, UpdateManager.curVersionCode, true).checkUpdateInfo();
			result = true;
		}
		return result;
	}

	// 外部接口让主Activity调用
	public void checkUpdateInfo() {
		// 这块有问题
		System.out.println("在checkUpdateInfo中");
		new CheckUpdateThread().start();
	}

	/* This Thread checks for Updates in the Background */
	public class CheckUpdateThread extends Thread {
		public void run() {
			jNetwork = JudgeNetwork.getInstance(mContext);
			System.out.println("在这里mobileConnected=" + jNetwork.isMobileConnected() + ",wifiConnected=" + jNetwork.isWifiConnected());
			if (jNetwork.isMobileConnected() || jNetwork.isWifiConnected()) {
				if (!autoCheckUpdateFlag)
					loadWindowHandler.sendMessage(loadWindowHandler.obtainMessage(0));

				XmlPullParser versionCodeParser = null;
				URL xmlUrl;
				try {
					xmlUrl = new URL(Client.BASE_URL + FileManager.VERSION_CODE_FILE_NAME);
					versionCodeParser = XmlPullParserFactory.newInstance().newPullParser();
					versionCodeParser.setInput(xmlUrl.openStream(), null);

					int eventType = -1;
					// Find Score records from XML
					while (eventType != XmlResourceParser.END_DOCUMENT) {
						if (eventType == XmlResourceParser.START_TAG) {
							// Get the name of the tag (eg scores or score)
							String strName = versionCodeParser.getName();
							if (strName.equals("version")) {
								String versionCode = versionCodeParser.getAttributeValue(null, "version_code");
								newVersionCode = Integer.valueOf(versionCode);
								apkFileName = versionCodeParser.getAttributeValue(null, "apk_file_name");
								newVersionName = versionCodeParser.getAttributeValue(null, "version_name");
								newVersionDescription = versionCodeParser.getAttributeValue(null, "version_description");
								newVersionDescription = newVersionDescription.replace('#', '\n');
								mHandler.sendMessage(Message.obtain(mHandler, MSG_VERSION_CODE, newVersionCode));
							}
							break;
						}
						eventType = versionCodeParser.next();
					}
				} catch (MalformedURLException e1) {
					// TODO Auto-generated catch block
					System.out.println("MalformedURLException");
					e1.printStackTrace();
				} catch (XmlPullParserException e) {
					// TODO Auto-generated catch block
					System.out.println("XmlPullParserException");
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					System.out.println("IOException");
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					System.out.println("Exception");
					e.printStackTrace();
				} finally {
					if (!autoCheckUpdateFlag)
						loadWindowHandler.sendMessage(loadWindowHandler.obtainMessage(1));
					if (newVersionCode == 0)
						mHandler.sendMessage(mHandler.obtainMessage(BAD_NETWORK));
				}
			} else {
				mHandler.sendMessage(mHandler.obtainMessage(BAD_NETWORK));
			}
		}
	};

	/* This Runnable creates a Dialog and asks the user to open the Market */
	private Runnable showUpdate = new Runnable() {
		public void run() {
			showRemindAboutNetwork();
		}
	};

	private void showRemindAboutNetwork() {
		// TODO Auto-generated method stub
		if (jNetwork.isWifiConnected() && showWindowFlag) {// 如果是wifi状态，直接下载
			showAskDownloadWindow();
		} else if (jNetwork.isMobileConnected() && showWindowFlag) {// 如果使用的是流量，提醒一下
			changeRemind = true;
			showAskDownloadWindow();
		} else if ((jNetwork.isMobileConnected() && !showWindowFlag) || (jNetwork.isWifiConnected() && !showWindowFlag)) {
			mHandler.sendMessage(mHandler.obtainMessage(DOWNLOADING));
		}
	}

	private void showAskDownloadWindow() {
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.window_ask_update, null);
		TextView remind1 = (TextView) v.findViewById(R.id.updateRemind1);
		TextView remind2 = (TextView) v.findViewById(R.id.updateRemind2);
		TextView title = (TextView) v.findViewById(R.id.title);
		TextView description = (TextView) v.findViewById(R.id.description);
		title.setText("发现新版本 " + newVersionName);
		description.setText(newVersionDescription);
		if (changeRemind) {
			remind1.setText("您的手机正在使用非wifi网络，可能会耗费较多的流量");
			remind2.setText("确定继续更新版本吗？");
		} else {
			remind1.setText("当前网络连接正常");
			remind2.setText("点击确定开始更新版本");
		}
		if (mUpdateAskWindow == null) {
			confirmButton = (TextView) v.findViewById(R.id.update_read_confirm_button);
			cancleButton = (TextView) v.findViewById(R.id.update_read_cancle_button);
			confirmButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					mUpdateAskWindow.dismiss();

					// 以下三行是原来的代码
					// Intent in = new Intent(mContext, UpdateService.class);
					// mContext.startService(in);
					// showWindowFlag = false;

					UpdateManager.shareUpdateExludingMarket(mContext);
				}

			});
			cancleButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					mUpdateAskWindow.dismiss();
					// mUpdateAskWindow = null;
				}
			});

			mUpdateAskWindow = new PopupWindow(v, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			mUpdateAskWindow.setFocusable(true);
			mUpdateAskWindow.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.transparent_bg_drawable));
			mUpdateAskWindow.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
					mMask.setVisibility(View.GONE);
				}
			});
		}
		mMask.setVisibility(View.VISIBLE);
		mUpdateAskWindow.showAtLocation(mMask, Gravity.CENTER, 0, 0);
		changeRemind = false;
	}

	public static void shareUpdate(Context context) {
		try {
			// Uri uri =
			// Uri.parse("market://search?q=pname:cn.edu.zjicm.wordsnet_d");
			Uri uri = Uri.parse("market://details?id=cn.edu.zjicm.wordsnet_d");
			Intent it = new Intent(Intent.ACTION_VIEW, uri);
			context.startActivity(it);
		} catch (ActivityNotFoundException ex) {
			// Log.e(TAG, "Error starting phone dialer intent.", ex);
			// Toast.makeText(this,
			// "Sorry, we couldn't find any app to place a phone call!",
			// Toast.LENGTH_SHORT).show();
		}
	}

	// 更新或评分时，在应用市场列表中排除google play "com.android.vending"
	public static void shareUpdateExludingMarket(Context context) {
		List<Intent> targetedShareIntents = new ArrayList<Intent>();
		Uri uri = Uri.parse("market://details?id=cn.edu.zjicm.wordsnet_d");
		Intent it = new Intent(Intent.ACTION_VIEW, uri);
		List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(it, 0);
		if (resInfo.isEmpty()) {
			Toast.makeText(context, "您未安装合适的应用市场软件", Toast.LENGTH_SHORT).show();
			return;
		} else {
			for (ResolveInfo info : resInfo) {
				Intent it1 = new Intent(Intent.ACTION_VIEW, uri);

				if (!info.activityInfo.packageName.equalsIgnoreCase("com.android.vending")) {
					it1.setPackage(info.activityInfo.packageName);
					targetedShareIntents.add(it1);
				}
			}

			if (targetedShareIntents.size() == 0) {
				Toast.makeText(context, "您未安装合适的应用市场软件", Toast.LENGTH_SHORT).show();
				return;
			}

			Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "选择要使用的应用");
			chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[] {}));
			context.startActivity(chooserIntent);
		}
	}

	// 下载知米听力，在应用市场列表中排除google play "com.android.vending"
	public static void downloadZhimiListenExludingMarket(Context context) {
		List<Intent> targetedShareIntents = new ArrayList<Intent>();
		Uri uri = Uri.parse("market://details?id=cn.edu.zjicm.listen");
		Intent it = new Intent(Intent.ACTION_VIEW, uri);
		List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(it, 0);
		if (resInfo.isEmpty()) {
			Toast.makeText(context, "您未安装合适的应用市场软件", Toast.LENGTH_SHORT).show();
			return;
		} else {
			for (ResolveInfo info : resInfo) {
				Intent it1 = new Intent(Intent.ACTION_VIEW, uri);

				if (!info.activityInfo.packageName.equalsIgnoreCase("com.android.vending")) {
					it1.setPackage(info.activityInfo.packageName);
					targetedShareIntents.add(it1);
				}
			}

			if (targetedShareIntents.size() == 0) {
				Toast.makeText(context, "您未安装合适的应用市场软件", Toast.LENGTH_SHORT).show();
				return;
			}

			Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "选择要使用的应用");
			chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[] {}));
			context.startActivity(chooserIntent);
		}
	}

	/**
	 * 这个方法暂时没用到
	 */
	private void showDownloadDialog() {
		if (mUpdateWindow == null) {
			// 加载window_update_progress布局
			final LayoutInflater inflater = LayoutInflater.from(mContext);
			View v = inflater.inflate(R.layout.window_update_progress, null);

			updateHideButton = (TextView) v.findViewById(R.id.update_hide_button);
			updateProgressBar = (ProgressBar) v.findViewById(R.id.update_progress_bar);
			updateProgressText = (TextView) v.findViewById(R.id.update_progress_text);
			updateHideButton.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					mUpdateWindow.dismiss();
					// interceptFlag = true;
				}
			});

			// 创建悬浮窗口
			mUpdateWindow = new PopupWindow(v, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			mUpdateWindow.setFocusable(true);
			mUpdateWindow.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.transparent_bg_drawable));
			mUpdateWindow.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
					mMask.setVisibility(View.GONE);
				}
			});
		}
		mMask.setVisibility(View.VISIBLE);
		mUpdateWindow.showAtLocation(mMask, Gravity.CENTER, 0, 0);
		// downloadApk();
	}

}